//
//  CalendarSignInViewController.m
//  CalendarDemo
//
//  Created by RYX on 2019/1/9.
//  Copyright © 2019 tuobu. All rights reserved.
//

#import "CalendarSignInViewController.h"
#import "CalendarSignInHeaderView.h"
#import "CalendarView.h"
#import "CalendarSignInFooterView.h"
#import "CalendarSignInStore.h"
#import "UINavigationBar+handle.h"

@interface CalendarSignInViewController ()
{
    NSString *currentYear;
    NSString *currentMonth;
}

@property (nonatomic,strong) CalendarSignInHeaderView *headerView;
@property (nonatomic,strong) CalendarView *calendarView;
@property (nonatomic,strong) CalendarSignInFooterView *footerView;
@property (nonatomic,strong) NSMutableArray *historyArr;

@end

@implementation CalendarSignInViewController

- (CalendarSignInHeaderView *)headerView{
    
    if (!_headerView) {
        
        MJWeakSelf
        _headerView = [[CalendarSignInHeaderView alloc] init];
        [_headerView setSignInBlock:^(BOOL hadSignIn) {
            
            if (hadSignIn) {
                
                [weakSelf showMBPError:@"今日已签到"];
            }else{
                
                [weakSelf signIn];
            }
        }];

    }
    
    return _headerView;
}

- (CalendarView *)calendarView{
    
    if (!_calendarView) {
        
        _calendarView = [[CalendarView alloc] init];
        MJWeakSelf
        [_calendarView setDateChangeBlock:^(NSString *currentDate) {
           
            NSArray *arr = [currentDate componentsSeparatedByString:@"-"];
            self->currentYear = arr[0];
            self->currentMonth = arr[1];
            [weakSelf getHistory];
        }];
    }
    
    return _calendarView;
}

- (CalendarSignInFooterView *)footerView{
    
    if (!_footerView) {
        
        MJWeakSelf
        _footerView = [[CalendarSignInFooterView alloc] init];
        [_footerView setTapBlock:^{
           
            NotOkViewController *VC = [[NotOkViewController alloc] init];
            [weakSelf.navigationController pushViewController:VC animated:YES];
        }];
    }
    
    return _footerView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithRed:239/255.0 green:113/255.0 blue:108/255.0 alpha:1.0] image:nil isOpaque:YES];
//    self.fd_interactivePopDisabled = YES;
}

//- (void)viewWillDisappear:(BOOL)animated{
//
//    [super viewWillDisappear:animated];
//    [self.navigationController.navigationBar navBarBackGroundColor:BLUECOLOR image:nil isOpaque:YES];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSDate *todayDate = [NSDate date];
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    dateFormatter.dateFormat=@"yyyy-MM";
    NSString *todayStr = [dateFormatter stringFromDate:todayDate];
    
    NSArray *arr = [todayStr componentsSeparatedByString:@"-"];
    currentYear = arr.firstObject;
    currentMonth = arr.lastObject;
    
    self.historyArr = [NSMutableArray array];
    
    [self setUI];
    
    //获取签到本月记录
    [self getHistory];
    
    //获取签到积分
    [self getIntegral];
    
}

- (void)setUI{
    
    [self setNavBarWithTitle:@"每日签到"];
    
    [self.view addSubview:self.headerView];
    
    [self.view addSubview:self.calendarView];
    
    [self.view addSubview:self.footerView];
    
    CGFloat headerScale = 0.4;
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(headerScale * SCREEN_WIDTH);
    }];
    
    CGFloat calendarScale = 0.86;
    [self.calendarView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(14);
        make.right.equalTo(self.view).offset(-14);
        make.top.equalTo(self.headerView.mas_bottom).offset(-35);
        make.height.mas_equalTo(calendarScale * (SCREEN_WIDTH - (28)));
    }];
    
    CGFloat footerScale = 0.3;
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(14);
        make.right.equalTo(self.view).offset(-14);
        make.bottom.equalTo(self.view);
        make.height.mas_equalTo(footerScale * (SCREEN_WIDTH - (28)) + iPhoneX_Bottom);
    }];
    
}

#pragma mark - 获取签到记录
- (void)getHistory{
    
    MJWeakSelf
    CalendarSignInStore *store = [[CalendarSignInStore alloc] init];
    
    NSString *customId = [UserDefaultsManager sharedInstance].user_id;
    [store getSignInListWithCustomId:customId andYear:currentYear andMonth:currentMonth Success:^(NSString *continued, NSArray *listArr) {
        
        NSDate *todayDate = [NSDate date];
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
        dateFormatter.dateFormat=@"yyyy-MM";
        NSString *todayStr = [dateFormatter stringFromDate:todayDate];
        
        NSArray *arr = [todayStr componentsSeparatedByString:@"-"];
        NSString *yy = arr.firstObject;
        NSString *mm = arr.lastObject;
        
        if ([self->currentYear isEqualToString:yy] && [self->currentMonth isEqualToString:mm]) {
            
            weakSelf.headerView.continued = continued;
        }
        
        self.historyArr = [NSMutableArray array];
        
        for (NSString *str in listArr) {
            
            NSString *time = [StrTool changeWithTime:str];
            
            NSArray *arr = [time componentsSeparatedByString:@" "];
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//            [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];
            NSDate *day = [dateFormatter dateFromString:arr.firstObject];
            
            [self.historyArr addObject:day];
            
            if ([self isSameDay:[NSDate date] date2:day]) {
                
                self.headerView.hadSignIn = YES;
            }
        }
        self.calendarView.listArr = self.historyArr;
        
    } Failure:^(NSError *error) {
       
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}


#pragma mark - 签到
- (void)signIn{
    
    MJWeakSelf
    CalendarSignInStore *store = [[CalendarSignInStore alloc] init];
    
    NSString *customId = [UserDefaultsManager sharedInstance].user_id;
    
    [store signInWithCustomId:customId Success:^{
        
        [weakSelf showMBPError:@"签到成功"];
        
        [weakSelf.historyArr addObject:[NSDate date]];
        weakSelf.calendarView.listArr = self.historyArr;
        
//        [weakSelf.calendarView.calendar selectDate:[NSDate date]];
        weakSelf.headerView.hadSignIn = YES;
        
        //签到积分
        [weakSelf getIntegral];
        
        //重置连续签到天数
        CalendarSignInStore *store = [[CalendarSignInStore alloc] init];
        
        NSDate *todayDate = [NSDate date];
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
        dateFormatter.dateFormat=@"yyyy-MM";
        NSString *todayStr = [dateFormatter stringFromDate:todayDate];
        
        NSArray *arr = [todayStr componentsSeparatedByString:@"-"];
        
        NSString *customId = [UserDefaultsManager sharedInstance].user_id;
        NSString *year = arr.firstObject;
        NSString *month = arr.lastObject;
        
        [store getSignInListWithCustomId:customId andYear:year andMonth:month Success:^(NSString *continued, NSArray *listArr) {
            
            weakSelf.headerView.continued = continued;
            
        } Failure:^(NSError *error) {
            
            [weakSelf showMBPError:[HttpTool handleError:error]];
        }];
        
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

#pragma mark - 获取签到积分
- (void)getIntegral{
    
    MJWeakSelf
    CalendarSignInStore *store = [[CalendarSignInStore alloc] init];
    [store searchIntegralWithCustomId:[UserDefaultsManager sharedInstance].user_id Success:^(NSString *integral) {
        
        self.footerView.integral = integral;
        
    } Failure:^(NSError *error) {
       
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
    
}

#pragma mark - 判断是否为同一天
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    
    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];
}


@end
